<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="订单号" prop="orderId">
        <el-input
          v-model="queryParams.orderNum"
          placeholder="请输入订单号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="客户姓名" prop="customName">
        <el-input
          v-model="queryParams.customName"
          placeholder="请输入客户姓名"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="供应商名称" prop="supplierName" label-width="85px">
        <el-input
          v-model="queryParams.supplierName"
          placeholder="请输入供应商名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="物流公司" prop="logisticsCompany">
        <el-input
          v-model="queryParams.logisticsCompany"
          placeholder="请输入物流公司"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="物流单号" prop="logisticsNumber">
        <el-input
          v-model="queryParams.logisticsNumber"
          placeholder="请输入物流单号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:logistics:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:logistics:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="logisticsList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column type="index" label="序号" align="center" />
      <el-table-column label="订单号" align="center" prop="orderNumber" label-width="95px">
        <template slot-scope="scope">
          <el-tag type="info" size="small">{{ scope.row.orderNumber }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="客户" align="center" prop="customName" label-width="30px">
        <template slot-scope="scope">
          <el-tag type="success" size="small">{{ scope.row.customName }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="供应商" align="center" prop="supplierName"  label-width="150px">
        <template slot-scope="scope">
          <el-tag type="primary" size="small">{{ scope.row.supplierName }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="物流路线" align="center" >
        <template slot-scope="scope">
          <span @click="showRoad(scope.row.supplierLongitude , scope.row.supplierLatitude, scope.row.customLongitude , scope.row.customLatitude)">
            <el-button
              type="primary"
              plain
              size="mini"
            >查看路线</el-button>
          </span>
        </template>
      </el-table-column>
      <el-table-column label="物流公司" align="center" prop="logisticsCompany" />
      <el-table-column label="物流单号" align="center" prop="logisticsNumber" label-width="180px">
        <template slot-scope="scope">
          <el-tag type="info" size="small">{{ scope.row.logisticsNumber }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="物流状态" align="center" prop="logisticsStatus" >
        <template slot-scope="scope">
          <el-tag type="success" size="small" v-if="scope.row.logisticsStatus === '2'">已收货</el-tag>
          <el-tag type="warning" size="small" v-if="scope.row.logisticsStatus === '1'">待收货</el-tag>
          <el-tag type="danger" size="small" v-if="scope.row.logisticsStatus === '0'">未发货</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:logistics:edit']"
          >物流信息</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:logistics:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改物流信息对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="物流公司" prop="logisticsCompany">
          <el-input v-model="form.logisticsCompany" placeholder="请输入物流公司" />
        </el-form-item>
        <el-form-item label="物流单号" prop="logisticsNumber">
          <el-input v-model="form.logisticsNumber" placeholder="请输入物流单号" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 查看地图显示 -->
    <el-dialog
      title="地图显示"
      :visible.sync="mapDialogVisible"
      width="70%"
      append-to-body
    >
      <div id="map" style="height: 400px;"></div>
    </el-dialog>

    <el-dialog
      title="路线显示"
      :visible.sync="roadDialogVisible"
      width="70%"
      append-to-body
    >
      <div id="road-map" style="height: 400px;"></div>
    </el-dialog>


  </div>
</template>

<script>
import { listLogistics, getLogistics, delLogistics, addLogistics, updateLogistics } from "@/api/system/logistics";
import AMapLoader from "@amap/amap-jsapi-loader";

export default {
  name: "Logistics",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 物流信息表格数据
      logisticsList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      mapDialogVisible: false,
      roadDialogVisible: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        orderId: null,
        orderNum: null,
        customId: null,
        customName: null,
        supplierId: null,
        supplierName: null,
        logisticsCompany: null,
        logisticsNumber: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        logisticsCompany: [
          { required: true, message: "物流公司不能为空", trigger: "blur" }
        ],
        logisticsNumber: [
          { required: true, message: "物流单号不能为空", trigger: "blur" }
        ]
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询物流信息列表 */
    getList() {
      this.loading = true;
      listLogistics(this.queryParams).then(response => {
        this.logisticsList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        logisticsId: null,
        orderId: null,
        customId: null,
        supplierId: null,
        logisticsCompany: null,
        logisticsNumber: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.logisticsId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加物流信息";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const logisticsId = row.logisticsId || this.ids
      getLogistics(logisticsId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改物流信息";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.logisticsId != null) {
            updateLogistics(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addLogistics(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const logisticsIds = row.logisticsId || this.ids;
      this.$modal.confirm('是否确认删除物流信息编号为"' + logisticsIds + '"的数据项？').then(function() {
        return delLogistics(logisticsIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/logistics/export', {
        ...this.queryParams
      }, `logistics_${new Date().getTime()}.xlsx`)
    },
    showMap(longitude, latitude) {
      this.mapLocation = {longitude, latitude};
      this.mapDialogVisible = true;
      window._AMapSecurityConfig = {
        securityJsCode: "d5bd1235caf6597e868d6c7d449552ed",
      };
      AMapLoader.load({
        key: 'f80e7ef04346ef76ed37aca535bbd864',
        version: '1.4.15',
        plugins: ['AMap.Geocoder']
      }).then(AMap => {
        const center = longitude && latitude
          ? [longitude, latitude]
          : [111.56, 40.79];

        this.map = new AMap.Map('map', {
          center,
          zoom: 15
        });

        this.marker = new AMap.Marker({
          position: center,
          icon: 'https://webapi.amap.com/theme/v1.3/markers/n/mark_b.png',
          map: this.map
        });
      }).catch(e => {
        console.error("高德地图初始化失败：", e);
      });
    },
    showRoad(originLongitude, originLatitude, destinationLongitude, destinationLatitude) {
      this.roadDialogVisible = true;
      window._AMapSecurityConfig = {
        securityJsCode: "d5bd1235caf6597e868d6c7d449552ed",
      };
        AMapLoader.load({
          key: 'f80e7ef04346ef76ed37aca535bbd864',
          version: '1.4.15',
          plugins: ['AMap.Driving']
        }).then(AMap => {
          const map = new AMap.Map('road-map', {
            viewMode: '2D',  //默认使用 2D 模式
            zoom:11,  //初始化地图层级
            center: [116.397428, 39.90923]  //初始化地图中心点
          });

          const startLngLat = [originLongitude, originLatitude] //起始点坐标
          const endLngLat = [destinationLongitude, destinationLatitude] //终点坐标
          const driving = new AMap.Driving({
            map: map,
            panel: "road-map", //参数值为你页面定义容器的 id 值<div id="my-panel"></div>
            extensions: 'all', //返回信息，可选值：base（基本信息）,all（所有信息）
          });
          //获取起终点规划线路
          driving.search(startLngLat, endLngLat, function (status, result) {
            if (status === "complete") {
              //status：complete 表示查询成功，no_data 为查询无结果，error 代表查询错误
              //查询成功时，result 即为对应的驾车导航信息
              console.log(result);
            } else {
              console.log("获取驾车数据失败：" + result);
            }
          });
        }).catch(e => {
          console.error("高德地图初始化失败：", e);
        });
    }

  }
};
</script>
